package cn.zhouchao.tran;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class TranConsumer {
    public static void main(String[] args) throws InterruptedException, MQClientException {
        // 1.创建一个消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("tran_consumer_group");

        // 2.设置NameServer的地址
        consumer.setNamesrvAddr("localhost:9876");

        // 3.订阅一个或者多个Topic，以及Tag来过滤需要消费的消息
        consumer.subscribe("tran_topic", "tran_tag");

        // 4.往消费者中设置我们的监听事件，编写怎么处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgslist, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
               try {
                   msgslist.forEach(e->{
                       System.out.println(new String(e.getBody(), StandardCharsets.UTF_8));
                   });
                   // 标记该消息已经被成功消费
                   return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
               }catch (Exception e) {
                   // 消费异常，我们告诉mq重新发送消息
                   return ConsumeConcurrentlyStatus.RECONSUME_LATER;
               }
            }
        });

        // 5.启动消费者实例
        consumer.start();
        System.out.println("Consumer Started.%n");
    }
}
